package com.app.conrtoller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.app.Filter.MyPascalNameFilter;
import com.app.domain.ExternalResponse;
import com.app.domain.UploadParameter;
import com.app.domain.YjData;
import com.app.domain.ezmeb.ApiResponse;
import com.app.domain.ezmeb.EzmData;
import com.app.service.EzmebService;
import com.app.service.UploadParameterService;
import com.app.service.UploadService;
import com.app.service.YjDataService;
import com.app.service.algs.TzbbUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 马山梁场
 */
@Slf4j
@RestController
@RequestMapping("/ezmeb")
public class EzmebUploadController {
    @Value("${yj.ezmeb.serviceHost}")
    private String serviceHost;
    @Value("${yj.ezmeb.tokenHost}")
    private String tokenHost;
    private static final String SUCCESS_STATE = "1";
    private static final String FAIL_STATE = "0";
    @Autowired
    YjDataService yjDataService;
    @Autowired
    UploadParameterService uploadParameterService;
    @Autowired
    UploadService uploadService;
    @Autowired
    EzmebService ezmebService;
    @Autowired
    TzbbUploadService tzbbUploadService;

    @RequestMapping("/upload")
    @ResponseBody
    public ExternalResponse upload(@RequestParam(value = "ids[]") String[] ids) throws InterruptedException, UnsupportedEncodingException {
        ExternalResponse externalResponse = null;

        // 使用try-catch处理可能的异常
        try {
            ApiResponse apiResponse = ezmebService.getToken(tokenHost);

            // 检查token是否过期
            if (apiResponse.getResult() == null || "".equals(apiResponse.getResult())) {
                externalResponse = new ExternalResponse(0, "token过期", "");
                return externalResponse;
            }

            String accessToken = apiResponse.getResult().getToken();
            AtomicInteger succTotal = new AtomicInteger(); // 使用AtomicInteger保证线程安全
            AtomicInteger failTotal = new AtomicInteger();
            StringBuffer responseContent = new StringBuffer();
            responseContent.append("本次共上传数据：【" + ids.length + "】条,");

            List<YjData> yjDataList = yjDataService.findList(ids);
            List<List<YjData>> groupList = yjDataList.stream().collect(Collectors.groupingBy(YjData::getBridge_code, Collectors.toList())).values().stream().collect(Collectors.toList());

            UploadParameter uploadParameter = uploadParameterService.findOne("37"); // 假设"37"是一个合法的、预先定义好的值
            for (List<YjData> yjData : groupList) {
                List<Integer> userIds = yjData.stream().map(o -> o.getId()).collect(Collectors.toList());
                EzmData ezmData = ezmebService.getEzmData(yjDataList, uploadParameter);
                String jsonString = JSON.toJSONString(ezmData,new MyPascalNameFilter(), SerializerFeature.WriteMapNullValue);
                System.out.printf(jsonString); // 注意：在生产环境中，可能需要替换为日志框架

                ApiResponse apiResponse1 = ezmebService.sendMessage(serviceHost, jsonString, accessToken);
                if (apiResponse1.getResult().getStatus() == 10000) {
                    for (Integer userId : userIds) {
                        updateState(SUCCESS_STATE, String.valueOf(userId)); // 使用常量代替硬编码值
                        succTotal.incrementAndGet();
                    }
                } else {
                    for (Integer userId : userIds) {
                        updateState(FAIL_STATE, String.valueOf(userId)); // 使用常量代替硬编码值
                        failTotal.incrementAndGet();
                    }
                }
            }
            responseContent.append("成功【" + succTotal.get() + "】条,失败" + failTotal.get() + "条");
            externalResponse = new ExternalResponse(0, responseContent.toString(), "");
        } catch (Exception e) {
            // 对于所有捕获的异常，可以记录日志并返回一个通用的错误响应
            System.err.println("上传过程中发生异常：" + e.getMessage());
            externalResponse = new ExternalResponse(0, "上传过程中发生错误", "");
        }

        return externalResponse;
    }


    @RequestMapping("/add")
    @ResponseBody
    public String add(@RequestParam("deviceCode") String deviceCode, @RequestParam("ductCode") String ductCode, @RequestParam("bridgeCode") String bridgeCode, @RequestParam("mudjackDate") String mudjackDate, @RequestParam("beginTime") String beginTime, @RequestParam("endTime") String endTime) {

        return tzbbUploadService.save(deviceCode, bridgeCode, ductCode, mudjackDate, beginTime, endTime);
    }

    private void updateState(String state, String id) {
        yjDataService.updateById(state, id);
    }
}